/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.internal.sdk.commands;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.DocumentProviderRegistry;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.ui.editor.validation.MarkerCreator;
import org.eclipse.xtext.ui.editor.validation.MarkerIssueProcessor;
import org.eclipse.xtext.ui.editor.validation.ValidationJob;
import org.eclipse.xtext.ui.validation.MarkerTypeProvider;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;

import com.google.inject.Inject;

import de.thwildau.tm.moses.internal.sdk.Activator;
 

/**
 * An action handler that validates all selected source documents of the correct syntax. This handler is more
 * comfortable validation handler with the same functionality than ValidateActionHandler.
 *
 * @author Thomas Kistel
 * @version $Revision: 760 $
 * @see org.eclipse.xtext.ui.editor.handler.ValidateActionHandler
 */
public class ValidateAllActionHandler extends AbstractHandler {
    
    @Inject
    private IResourceValidator resourceValidator;
    @Inject 
    private MarkerCreator markerCreator;

    /* (non-Javadoc)
     * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
     */
    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelectionChecked(event);
        @SuppressWarnings("unchecked")
        Iterator<Object> iterator = (Iterator<Object>) selection.iterator();
        Map<IFile, Job> filesToValidate = new Hashtable<IFile, Job>();
        IProgressMonitor pm = Job.getJobManager().createProgressGroup();
        try {
            /*
             * Iterate over all selected elements and check whether it is a 
             * - file
             * - java package
             * - source root folder
             */
            while (iterator.hasNext()) {
                Object object = iterator.next();
                if(object instanceof IFile) {
                    startJob((IFile) object, filesToValidate);
                } else if(object instanceof IPackageFragment) {
                    startJob((IPackageFragment) object, filesToValidate);
                } else if(object instanceof IPackageFragmentRoot) {
                    startJob((IPackageFragmentRoot) object, filesToValidate);
                }
            }
            
            pm.beginTask("Validating all selected files", filesToValidate.size());
            int ticks = 0;
            for (Entry<IFile, Job> entry : filesToValidate.entrySet()) {
                ticks++;
                Activator.debugInfo("Validate " + entry.getKey().getProjectRelativePath().toOSString());
                Job job = entry.getValue();
                job.setProgressGroup(pm, ticks);
                job.schedule();
            }
            
            for(Entry<IFile, Job> entry : filesToValidate.entrySet()) {
                try {
                    entry.getValue().join();
                } catch (InterruptedException e) {
                    Activator.logWarning("The validation job of " + entry.getKey().getProjectRelativePath().toOSString() + " was interrupted.");
                }
            }
            
        } catch (CoreException e) {
            throw new ExecutionException("Could not validate selected files.", e);
        } finally {
            pm.done();
        }
        return null;
    }
    
    private void startJob(IJavaElement javaElement, Map<IFile, Job> filesToValidate) throws CoreException {
        IResource resource = javaElement.getResource();
        if(resource != null && resource.getType() == IResource.FOLDER) {
            startJob((IFolder) resource, filesToValidate);
        }
    }
    
    private void startJob(IFolder folder, Map<IFile, Job> filesToValidate) throws CoreException {
        IResource[] members = folder.members();
        for (IResource res : members) {
            if(!isHidden(res)) {
                if(res.getType() == IResource.FILE) {
                    startJob((IFile) res, filesToValidate);
                } else if(res.getType() == IResource.FOLDER) {
                    startJob((IFolder) res, filesToValidate);
                }
            }
        }
    }
    
    private void startJob(IFile file, Map<IFile, Job> filesToValidate) throws CoreException, PartInitException {
        // do not double check files
        if(filesToValidate.containsKey(file) || isHidden(file))
            return;
        
        MarkerIssueProcessor markerIssueProcessor = new MarkerIssueProcessor(file, markerCreator, new MarkerTypeProvider());
        IXtextDocument xtextDocument = find(file); 
        if(xtextDocument == null) {
            Activator.logWarning("Could not find document for file " + file.getName());
            return;
        }
        
        ValidationJob validationJob = new ValidationJob(resourceValidator, xtextDocument, markerIssueProcessor, CheckMode.ALL);
        filesToValidate.put(file, validationJob);
    }
    
    private IXtextDocument find(IFile file) throws CoreException, PartInitException {
        DocumentProviderRegistry providerReg = DocumentProviderRegistry.getDefault();
        FileEditorInput editorInput = new FileEditorInput(file);
        IDocumentProvider documentProvider = providerReg.getDocumentProvider(editorInput);
        documentProvider.connect(editorInput);
        IDocument document = documentProvider.getDocument(editorInput);
        if(document instanceof IXtextDocument)
            return (IXtextDocument) document;
        return null;
    }
    
    private boolean isHidden(IResource resource) {
        if(resource.isHidden())
            return true;
        else if(resource.getName().startsWith("."))
            return true;
        else
            return false;
    }
}
